import frappe
from frappe.core.report.database_storage_usage_by_tables.database_storage_usage_by_tables import (
    execute as original_execute,
    COLUMNS
)

def execute(filters=None):
    """获取数据库表存储使用情况

    Args:
        filters: 过滤条件（未使用）

    Returns:
        tuple: (列定义, 数据列表)
    """
    if frappe.db.db_type != "dm":
        return original_execute(filters)

    frappe.only_for("System Manager")

    data = frappe.db.sql(
        """
        SELECT 
            table_name AS "table",
            round(((bytes + index_bytes) / 1024 / 1024), 2) AS "size",
            round((bytes / 1024 / 1024), 2) AS "data_size",
            round((index_bytes / 1024 / 1024), 2) AS "index_size"
        FROM (
            SELECT 
                t.table_name,
                SUM(s.bytes) AS bytes,
                SUM(CASE WHEN s.type = 1 THEN s.bytes ELSE 0 END) AS index_bytes
            FROM dba_tables t
            JOIN dba_segments s ON s.segment_name = t.table_name
            WHERE t.owner = USER
            GROUP BY t.table_name
        ) t
        ORDER BY (bytes + index_bytes) DESC
        """,
        as_dict=1,
    )
    return COLUMNS, data
